package db

import (
	"errors"
	"log"
	"server_cluster/battle/sharemem"
	"strconv"
	"strings"
)

type Config_battle struct {
	Id      int32  `gorm:"primary_key;column:Id;autoIncrement:false" csv:"Id"`
	Monster string `gorm:"column:Monster" csv:"Monster"`
}

func (tmp *Config_battle) TableName() string {
	return "config_battle"
}

func (tmp *Config_battle) getAll() ([]*Config_battle, error) {
	var data []*Config_battle
	result := Conn.Find(&data)
	return data, result.Error
}

func (tmp *Config_battle) LoadData() error {
	data, err := tmp.getAll()
	if err != nil {
		return err
	}
	var myshm = &(sharemem.Myshm.Cfg.Bt)
	for key, value := range data {
		if key >= sharemem.BATTLE_MAX || value.Id <= 0 {
			return errors.New("config_battle format error 1")
		}
		myshm[key].Id = value.Id
		if len(value.Monster) == 0 {
			return errors.New("config_battle format error 11")
		}

		a_list := strings.Split(value.Monster, ";")
		if len(a_list) > sharemem.BATTLE_MONSTER {
			return errors.New("config_battle format error 111")
		}
		for k, v := range a_list {
			arg, err := strconv.Atoi(v)
			if err != nil {
				return errors.New("config_battle format error 1111")
			}
			myshm[key].Monster[k] = int32(arg)
		}
	}
	log.Println("load config_battle completed.")
	return nil
}
